package com.zzyl.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.ws.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Struct;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 设备上报数据报警规则过滤
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AlertJob {

    @Autowired
    AlertRuleMapper alertRuleMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    DeviceMapper deviceMapper;
    @Autowired
    AlertDataMapper alertDataMapper;
    @Autowired
    WebSocketServer webSocketServer;

    @Scheduled(cron = "0/20 * * * * ?")
    public void deviceDataAlertFilter() {
        log.info("定时任务，检测设备上报数据");
        //1,判断是否有有效的规则
        //查询所有报警规则，是否为空
        List<AlertRule> alertRules = alertRuleMapper.selectAll();
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }

        //2,判断redis中是否有数据object：指的是redis中的hashmap中的value值，value的值是设备上报的数据（多个属性）
        List<Object> values = stringRedisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)) {
            return;
        }
        //3,获取redis中所有设备的所有属性上报的数据，List<DeviceDataVo>
        List<DeviceDataVo> redisAllData = new ArrayList<>();

        values.forEach(jsonStr -> {
            //jsonStr表示某一个设备上报的一次数据
            List<DeviceDataVo> deviceDataVos = JSON.parseArray(jsonStr.toString(), DeviceDataVo.class);
            //将deviceDataVos添加到redisAllData中
            CollectionUtil.addAll(redisAllData, deviceDataVos);
        });
        //4,对集合中的每个属性做检测
        redisAllData.forEach(this::alterFilter);
    }

    private void alterFilter(DeviceDataVo deviceDataVo) {
        log.info("=================================================deviceDataVo,{}", deviceDataVo);
        //1,判断设备的数据上报时间是否超过1分钟
        if (LocalDateTimeUtil.now().plusMinutes(-1).isAfter(deviceDataVo.getAlarmTime())) {
            return;
        }

        //2,查询报警规则：针对该某一个设备的+针对该产品的全部设备
        List<AlertRule> alertRules1 = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(),
                deviceDataVo.getIotId(),
                deviceDataVo.getProductKey());

        List<AlertRule> alertRules2 = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(),
                "-1",//表示该产品下使用的设备
                deviceDataVo.getProductKey());

        Collection<AlertRule> alertRuleAll = CollUtil.addAll(alertRules1, alertRules2);

        //3,判断报警规则是否为空
        if (CollUtil.isEmpty(alertRuleAll)) {
            return;
        }

        //4,使用规则对数据做校验
        alertRuleAll.forEach(alertRule -> {
            deviceDataAlarmHandler(alertRule, deviceDataVo);
        });
    }

    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceDataVo deviceDataVo) {
        //第一层校验：判断设备数据上报时间是否在规则的生效时间范围
        LocalTime startTime = LocalTime.parse(alertRule.getAlertEffectivePeriod().split("~")[0]);
        LocalTime endTime = LocalTime.parse(alertRule.getAlertEffectivePeriod().split("~")[1]);

        LocalTime alarmTime = deviceDataVo.getAlarmTime().toLocalTime();

        //上报时间在开始时间之前，或者在结束时间之后，不需要处理，直接结束
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            return;
        }

        //第二层校验，判断设备数据值是否触发规则阈值
        String operator = alertRule.getOperator();
        Double dataValue = Double.valueOf(deviceDataVo.getDataValue());
        Double ruleValue = Double.valueOf(alertRule.getValue());

        //将两个值比较大小
        int compare = dataValue.compareTo(ruleValue);
        //如果设备值比规则值大，并且运算符为大于，或者设置值比规则值小，并且运算符为小于，则触发阈值
        if ((compare >= 0 && StrUtil.equals(">=", operator))
                || (compare < 0 && StrUtil.equals("<", operator))) {
            //说明设备数据触发了规则的阈值
            log.info("说明设备数据触发了规则的阈值：{} {}", alertRule, deviceDataVo);
        } else {
            return;
        }

        //第三层校验：判断沉默周期
        String silentCycleRedisKey = CacheConstants.ALERT_SILENT_CYCLE + deviceDataVo.getIotId() + deviceDataVo.getFunctionId() + alertRule.getId();

        //去redis中查询，是否存在指定的Key
        Boolean hasKey = stringRedisTemplate.hasKey(silentCycleRedisKey);
        if (hasKey) {
            //保持沉默，不需要处理
            return;
        }

        //第四层校验，判断持续周期
        String triggerCountRedisKey = CacheConstants.ALERT_TRIGGER_COUNT + deviceDataVo.getIotId() + deviceDataVo.getFunctionId() + alertRule.getId();
        //去redis中查询值
        String count = stringRedisTemplate.opsForValue().get(triggerCountRedisKey);
        //如果count为空，当作0看待
        count = StrUtil.nullToDefault(count, "0");
        int triggerCount = Integer.parseInt(count) + 1;

        //和规则的持续周期比较
        if (triggerCount < alertRule.getDuration()) {
            //说明还不满足持续周期，将数值存入redis
            stringRedisTemplate.opsForValue().set(triggerCountRedisKey, String.valueOf(triggerCount));
            return;
        }


        //////////////////报警逻辑处理
        log.info("已检测到设备数据满足报警条件：{}{}", alertRule, deviceDataVo);

        /**
         * 报警需要做的事情；
         * 1)添加沉默周期，时效性
         * 2)删除持续周期
         * 3)先查询通知人，添加报警数据
         */

        //1添加沉默周期，时效性
        stringRedisTemplate.opsForValue().set(silentCycleRedisKey, "true", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //2删除持续周期
        stringRedisTemplate.delete(triggerCountRedisKey);

        //3先查询通知人，添加报警数据                3个sql：随身设备，床位，房间
        //判断设备绑定位置
        Integer physicalLocationType = deviceDataVo.getPhysicalLocationType();//1房间2床位-1老人
        log.info("========================================================================================physicalLocationType{}", physicalLocationType);

        List<Long> userIds = null;


        if (ObjectUtil.equals(physicalLocationType, 1)) {//1房间 固定设备
            userIds = userRoleMapper.selectUserIdsByRoleName("维修工");
        }
        log.info("========================================================================================userIds1{}", userIds);
        if (ObjectUtil.equals(physicalLocationType, 2)) {//2床位   固定设备
            userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceDataVo.getIotId());
        }
        log.info("========================================================================================userIds2{}", userIds);
        if (ObjectUtil.equals(physicalLocationType, -1)) {
            userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceDataVo.getIotId());
        }
        log.info("========================================================================================userIds3{}", userIds);
        //查询管理员
        List<Long> adminIds = userRoleMapper.selectUserIdsByRoleName("超级管理员");
        log.info("========================================================================================adminIds{}", adminIds);
        //最终通知的用户id集合
        Collection<Long> allUserIds = CollUtil.addAll(userIds, adminIds);

        //Collection<Long> allUserIds = CollUtil.addAll(userIds, adminIds);
        log.info("========================================================================================{}", allUserIds);

        if (CollUtil.isEmpty(allUserIds)) {
            return;
        }
        log.info("==========================================================================================");
        insertAlertData(allUserIds, deviceDataVo, alertRule);


    }

    private void insertAlertData(Collection<Long> allUserIds, DeviceDataVo deviceDataVo, AlertRule alertRule) {
        //遍历用户集合，给每个用户添加报警数据
        allUserIds.forEach(userId -> {
            AlertData alertData = new AlertData();

            BeanUtil.copyProperties(alertRule, alertData);
            BeanUtil.copyProperties(deviceDataVo, alertData);

            alertData.setAlertRuleId(alertRule.getId()); //报警规则id

            String alertReason = String.format("%s %s %s ,持续周期 %s",
                    alertRule.getFunctionName(),
                    alertRule.getOperator(),
                    alertRule.getValue(),
                    alertRule.getDuration());

            alertData.setAlertReason(alertReason);
            alertData.setType(alertRule.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(userId);
            alertData.setDeviceDescription(deviceDataVo.getRemark());

            alertDataMapper.insert(alertData);
            sendAlertMessage(allUserIds, deviceDataVo, alertRule);
        });
    }

    private void sendAlertMessage(Collection<Long> allUserIds, DeviceDataVo deviceDataVo, AlertRule alertRule) {
        AlertNotifyDto alertNotifyDto = AlertNotifyDto.builder().build();

        BeanUtil.copyProperties(deviceDataVo, alertNotifyDto);
        BeanUtil.copyProperties(alertRule, alertNotifyDto);

        alertNotifyDto.setIsAllConsumer(false);
        alertNotifyDto.setNotifyType(1);
        alertNotifyDto.setVoiceNotifyStatus(1);

        webSocketServer.sendMessageToConsumer(alertNotifyDto, new ArrayList<>(allUserIds));
    }

}